const router = require("express").Router();
const { ScreeningTimes, ScreeningRoom, Seat } = require('@/models')
const expressJoi = require('@escook/express-joi')
const { data } = require('@/utils/send')
const { add, put, del } = require('@/joi/time')

router.get('/', async (req, res) => {
    const { id } = req.query
    const where = { is_delete: 0 }
    const order = [['id', 'desc']]
    const query = id ? ScreeningTimes.findOne({ where: { id } }) : ScreeningTimes.findAll({ where, order })
    const result = await query
    if (!result) return res.cc('获取场次信息失败')
    const message = id ? '获取场次信息成功' : '获取场次列表成功'
    const datas = data({ message, data: result })
    res.send(datas)
    res.locals.data = datas;
})
router.post('/', expressJoi(add), async (req, res) => {
    try {
        const { auditorium_id } = req.body
        const [room, info] = await Promise.all([await ScreeningRoom.findOne({ where: { id: auditorium_id } }), await ScreeningTimes.create({ ...req.body })])
        if (!info) return res.cc('添加失败')
        const RoomSeats = Addseat(room.seats);
        await Seat.create({ time_id: info.id, seatinfo: RoomSeats });
        const datas = data({ message: '添加场次成功' })
        res.send(datas)
        res.locals.data = datas;
    } catch (error) {
        res.cc(error)
    }
})
router.put('/', expressJoi(put), async (req, res) => {
    try {
        const { id } = req.body
        const cinema = await ScreeningTimes.findOne({
            where: { id }
        })
        if (!cinema) return res.cc('该场次不存在')
        const result = await cinema.update(req.body)
        if (!result) return res.cc('修改失败')
        const datas = data({ message: '修改场次成功' })
        res.send(datas)
        res.locals.data = datas;
    } catch (error) {
        res.cc(error)
    }
})
router.delete('/', expressJoi(del), async (req, res) => {
    try {
        let { id } = req.query
        id = Number(id)
        console.log(id);
        const cinema = await ScreeningTimes.findOne({
            where: { id }
        })
        if (!cinema) return res.cc('该场次不存在')
        const result = await cinema.update({ is_delete: 1 })
        if (!result) return res.cc('删除失败')
        const datas = data({ message: '删除场次成功' })
        res.send(datas)
        res.locals.data = datas;
    } catch (error) {
        res.cc(error)
    }
})
function Addseat(seats) {
    let seat = []
    for (let i = 0; i < seats; i++) {
        seat.push({ id: i + 1, status: 0 })
    }
    return seat
}
module.exports = router